package hydrap2p.library;

import hydrap2p.ServiceLocation;

import java.util.List;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

/**
 * Represents one registered HashGenerator
 * @author Hufman
 *
 */
public class HasherThrift implements Hasher{
	private HashGenerator.Client connection;
	private ServiceLocation location;
	
	/**
	 * Creates a new Metadater object, and tries to connect to it
	 * If it fails to cnonect, it will through an exception
	 * @param location
	 * @throws TException 
	 */
	public HasherThrift(ServiceLocation location) throws TException
	{
		// Special case for the Unit Test
		// Don't connect to null locations
		if (location==null)
			return;
		
		this.location=location;

		TTransport transport = new TSocket(location.address,location.port);
		transport.open();
		connection=new HashGenerator.Client(new TBinaryProtocol(transport));
		
		if (!connection.supportedInterfaces().contains("HashGenerator"))
			throw new TException("Module does not implement HashGenerator");
	
	}
	
	/**
	 * Calculates the hash for the given range on the given shared item 
	 * Throws an exception if something bad happens, which usually signals that this Hasher no longer works
	 * Return null if no valid hash could be generated
	 * @param filename
	 * @return
	 * @throws TException
	 */
	public String getHash(SharedItemInfo item, Range range) throws TException
	{
		try {
			return connection.getHash(item, range);
		} catch (FileNotFound e) {
			return null;
		}
	}
	/**
	 * Calculates any available hashes for this shared item, which may be an empty list
	 * Throws an exception if something bad happens, which usually signals that this Hasher no longer works
	 * Return null if no valid hash could be generated
	 * @param filename
	 * @return
	 * @throws TException
	 */
	public List<HashData> getHashes(SharedItemInfo item) throws TException
	{
		try {
			return connection.getHashes(item);
		} catch (FileNotFound e) {
			return null;
		}
	}
}
